package com.bawei.module_goods.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_goods.R
import com.bawei.module_goods.entity.ShoppingCartDisplayItem
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners

class ShoppingCartAdapter(
    private var items: MutableList<ShoppingCartDisplayItem> = mutableListOf(),
    private val onItemCheckedChange: (Int, Boolean) -> Unit,
    private val onCountChange: (Int, Int) -> Unit,
    val onSwipeAction: ((position: Int, action: SwipeAction) -> Unit)? = null
) : RecyclerView.Adapter<ShoppingCartAdapter.CartViewHolder>() {

    val checkedMap = mutableMapOf<Int, Boolean>()
    private var isBatchUpdating = false // 添加批量更新标志
    // 使用cartId作为键的选择状态映射，用于在数据更新时保持选择状态
    private val checkedByCartId = mutableMapOf<Int, Boolean>()
    // 新增：规格点击回调接口
    var onSpecClick: ((position: Int, item: ShoppingCartDisplayItem) -> Unit)? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cart_goods, parent, false)
        return CartViewHolder(view)
    }

    override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
        val item = items[position]
        holder.tvName.text = item.goodsName
        holder.tvSpec.text = "规格：${item.goodsSkuId ?: "-"}"
        // 新增：规格点击事件
        holder.tvSpec.setOnClickListener {
            onSpecClick?.invoke(position, item)
        }
        holder.tvPrice.text = "￥${item.price ?: 0.0}"
        val safeNumber = if (item.number > 0) item.number else 1
        holder.tvCount.text = safeNumber.toString()
        holder.checkbox.setOnCheckedChangeListener(null)
        holder.checkbox.isChecked = checkedMap[position] ?: false
        holder.checkbox.setOnCheckedChangeListener { _, isChecked ->
            checkedMap[position] = isChecked
            // 同时更新基于cartId的选择状态
            checkedByCartId[item.cartId] = isChecked
            // 只有在非批量更新时才触发回调
            if (!isBatchUpdating) {
                onItemCheckedChange(position, isChecked)
            }
        }
        holder.btnAdd.setOnClickListener {
            val count = safeNumber + 1
            android.util.Log.d("CartLog", "btnAdd clicked, position=$position, newCount=$count")
            onCountChange(position, count)
        }
        holder.btnMinus.setOnClickListener {
            if (safeNumber > 1) {
                android.util.Log.d("CartLog", "btnMinus clicked, position=$position, newCount=${safeNumber - 1}")
                onCountChange(position, safeNumber - 1)
            }
        }
        val imageUrl = item.goodsImage
        Glide.with(holder.ivImage.context)
            .load(if (imageUrl.isNullOrEmpty()) R.mipmap.ic_launcher else imageUrl)
            .placeholder(R.mipmap.ic_launcher)
            .transform(RoundedCorners(16))
            .into(holder.ivImage)
    }

    override fun getItemCount(): Int = items.size

    fun setData(newItems: List<ShoppingCartDisplayItem>) {
        // 更新数据
        items = newItems.toMutableList()
        
        // 基于cartId恢复选择状态
        checkedMap.clear()
        for (i in items.indices) {
            val item = items[i]
            // 如果这个cartId之前是选中的，则保持选中状态
            if (checkedByCartId[item.cartId] == true) {
                checkedMap[i] = true
            }
        }
        
        notifyDataSetChanged()
    }

    fun setAllChecked(checked: Boolean) {
        isBatchUpdating = true // 开始批量更新
        for (i in items.indices) {
            checkedMap[i] = checked
            // 同时更新基于cartId的选择状态
            checkedByCartId[items[i].cartId] = checked
        }
        notifyDataSetChanged()
        isBatchUpdating = false // 结束批量更新
    }

    fun getCheckedItems(): List<ShoppingCartDisplayItem> {
        return items.filterIndexed { index, _ -> checkedMap[index] == true }
    }

    fun getItem(position: Int): ShoppingCartDisplayItem? {
        return items.getOrNull(position)
    }

    // 清空所有选择状态
    fun clearCheckedState() {
        checkedMap.clear()
        checkedByCartId.clear()
        notifyDataSetChanged()
    }

    enum class SwipeAction {
        DELETE, COLLECT
    }

    class CartViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val checkbox: CheckBox = itemView.findViewById(R.id.checkboxItem)
        val ivImage: ImageView = itemView.findViewById(R.id.ivGoodsImage)
        val tvName: TextView = itemView.findViewById(R.id.tvGoodsName)
        val tvSpec: TextView = itemView.findViewById(R.id.tvGoodsSpec)
        val tvPrice: TextView = itemView.findViewById(R.id.tvGoodsPrice)
        val tvCount: TextView = itemView.findViewById(R.id.tvGoodsCount)
        val btnAdd: TextView = itemView.findViewById(R.id.btnAdd)
        val btnMinus: TextView = itemView.findViewById(R.id.btnMinus)
    }
} 